package run.iget.webcoket.config;

import java.util.Objects;

import javax.annotation.Resource;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.tio.websocket.server.WsServerStarter;

import cn.hutool.core.util.StrUtil;
import run.iget.framework.propertity.ApiPathPrefixUtils;
import run.iget.framework.propertity.ModuleProperties;
import run.iget.webcoket.constant.WSConst;
import run.iget.webcoket.handler.WsMsgHandler;

/**
 * 代码千万行，注释第一行，注释不规范，迭代两行泪
 * ---------------类描述-----------------
 * controller请求前缀配置
 * ---------------类描述-----------------
 *
 * @author 大周
 * @date 2023/1/18 12:13
 */
@Configuration
@ConditionalOnProperty(prefix = WSConst.MODULE_NAME, value = ModuleProperties.CONDITIONAL_ON_PROPERTY_VALUE_NAME)
public class WSWebMvcConfigurer implements WebMvcConfigurer, ApplicationRunner {

    @Resource
    private WebSocketProperties properties;

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        // 为指定包下的controller添加前缀
        ApiPathPrefixUtils.addApiPathPrefix(properties, configurer, WSConst.CONTROLLER_PACKAGE_NAME);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        if (!Boolean.TRUE.equals(properties.getEnable()) || Objects.isNull(properties.getPort())) {
            return;
        }

        if (Objects.nonNull(properties.getShowMsg())) {
            WSConst.SHOW_MSG = properties.getShowMsg();
        }

        if (StrUtil.isNotBlank(properties.getUserSign())) {
            WSConst.CONNECT_REQ_USER_ID = properties.getUserSign();
        }

        // 设置处理器
        WsServerStarter wsServerStarter = new WsServerStarter(properties.getPort(), new WsMsgHandler());
        // 获取到ServerTioConfig
        WSConst.TIO_SERVER_CONFIG = wsServerStarter.getServerTioConfig();
        // 设置心跳超时时间，默认：1000 * 120
        if (Objects.nonNull(properties.getHeartbeatTimeout())) {
            WSConst.TIO_SERVER_CONFIG.setHeartbeatTimeout(properties.getHeartbeatTimeout());
        }
        // 启动
        wsServerStarter.start();
    }
}
